package kr.co.ham.control;

import java.awt.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

import javax.swing.JFileChooser;

import kr.co.ham.common.ImgFileFilter;
import kr.co.ham.view.Variables;

import org.apache.log4j.Logger;
/**
 * @see 파일 서비스
 * @author hamjjang
 *@since 2013. 05. 05
 * @version 1.0
 */

public class FileServiceImpl implements FileService {

	private static Logger logger = Logger.getLogger("filelog"); 
	public ImgFileFilter fileFilter = new ImgFileFilter();
	
	@Override
	public boolean setFileNmChange(String strOrgPath, String strNewPath, String strOption, String strUsrDef){
		ArrayList<File> orgFileLst = this.getFileList(strOrgPath);
		String chgFileNm = null;
		for(File of : orgFileLst){
			Variables.txt_stat.append("["+of.getPath()+"] ");
			chgFileNm = this.getFileName(of, strOption, strUsrDef);	// 파일명 가져오기.
			// 파일 복사
			String newFilefullName = strNewPath + '/' + chgFileNm ;
			Variables.txt_stat.append("을 ["+newFilefullName+"] ");
			File file = new File(newFilefullName);
			String[] ret = this.setFileCopy(of, file);
			if(ret[0] == "0"){
				Variables.txt_stat.append("의 변경은 "+ret[1]+" 실패하였습니다.\n");
			}else{
				Variables.txt_stat.append("으로 변경에 성공하였습니다.\n");
			}
		}
		return true;
	}
	
	@Override
	public ArrayList<File> getFileList(String path) {
		File dir = new File(path);
		File[] fileList = dir.listFiles();
		ArrayList<File> imgFileList = new ArrayList<>();
		
		try {
			int index = 0;
			for(File f :fileList){
				if(f.isFile()){
					logger.debug("file Name : " + f.getName());
					logger.debug(" image file check : " + fileFilter.accept(f, f.getName()) );
					if(fileFilter.accept(f, f.getName())){
						imgFileList.add(index, f);
						index++;
					}
				}
			}
			logger.debug("File List > " + imgFileList.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return imgFileList;
	}
	
	@Override
	public String getFileName(File file, String option, String userDefName) {
		// TODO Auto-generated method stub
		// option N : 없음 , C:생성일자, M:수정일자, U:사용자지정, E:기타
		BasicFileAttributes fileAttributes = null;
		Path path =  Paths.get(file.getPath());
		String fileName = "";
		String orgFileName = file.getName() ;
		String fileEndNm = orgFileName.substring(orgFileName.lastIndexOf("."), orgFileName.length());
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date();
		try{
			logger.debug("path : " + path);
			fileAttributes =  Files.readAttributes(path, BasicFileAttributes.class);
			
			switch(option){
				case "C":
					String cerateDate = dateFormat.format(fileAttributes.creationTime().toMillis() );
					fileName = cerateDate;
					break;
				case "M":
					fileName = dateFormat.format(file.lastModified());
					break;
				case "U":
					fileName = userDefName + "_" + Variables.fileIndex++;
					break;
				case "E":
					fileName = dateFormat.format(date);
					break;
				default :
					fileName = null;
					break;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		logger.debug("  file Name : " +  fileName + fileEndNm);
		return  fileName + fileEndNm ;
	}

	@Override
	public String[] setFileCopy(File orgFile, File newFile) {
		// TODO Auto-generated method stub
		String retArr[] = new String[2];
		boolean result = false;
		
		FileInputStream inputStream = null; 
		FileOutputStream outputStream = null; 
		
		try {
			boolean chkDir = false;
			if(!newFile.isDirectory()){
				chkDir = newFile.mkdirs();
			}
			if(!chkDir){
				inputStream = new FileInputStream(orgFile); 
				outputStream = new FileOutputStream(newFile);
				
				FileChannel fileChlIn = inputStream.getChannel(); 
				FileChannel fileChlOut = outputStream.getChannel() ; 
				
				long size = 0; 
				
				size = fileChlIn.size(); 
				
				if(newFile.isFile()){
					retArr[1] = "파일이 이미 존재합니다.";
					result = false;
				}else{
					// 파일 변경
					fileChlIn.transferTo(0, size, fileChlOut);
					result = true;
				}
				fileChlOut.close(); 
				fileChlIn.close(); 
				outputStream.close(); 
				inputStream.close();
			}else{
				result = false;
				retArr[1] = "디렉토리 생성에 실패하였습니다.";
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		retArr[0] = result? "1" : "0";
		return retArr ; 
	}

	@Override
	public String getFileOpen(Component obj) {
		// TODO Auto-generated method stub
		String filePath = "";
		JFileChooser fileChooser = new JFileChooser("/");
		
		fileChooser.setDialogTitle("폴더선택"); // 창 제목 셋팅
		fileChooser.setApproveButtonText("선택");	// 열기 또는 저장 버튼 텍스트를 지정한다.
		fileChooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY);
		fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("폴더", "."));
		
		int result = fileChooser.showOpenDialog(obj);
		File file = null;
		if(result == JFileChooser.APPROVE_OPTION){
			file = fileChooser.getSelectedFile();
			filePath = file.getPath();
		}
		
		return filePath;
	}

	@Override
	public boolean setDelectOrgFiles(String strOrgPath) {
		// TODO Auto-generated method stub
		boolean result = false; 
		
		ArrayList<File> orgFileLst = this.getFileList(strOrgPath);
		for(File file : orgFileLst ){
			if (file.delete()) {   
		    	result = true;
		    }   
		}
	    return result ; 
	}

}
